package fair.controllerMobile;

import com.alibaba.dubbo.config.annotation.Reference;
import fair.constant.MessageConstant;
import fair.constant.RedisMessageConstant;
import fair.entity.Result;
import fair.pojo.Order;
import fair.service.OrderService;
import fair.utils.TXSMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author fair_wu
 * @version v1.0
 * @package fair.controllerMobile
 * @date 2021-01-28 下午 21:30
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService service;

    @Autowired
    private JedisPool jedisPool;

    @PostMapping("/submit")
    public Result submit(@RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        String orderDate = (String) map.get("orderDate");
        String[] split = orderDate.split("-");
        String code = split[1] + split[2];
        if (codeInRedis != null && validateCode != null && codeInRedis.equals(validateCode)){
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            try {
                result = service.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }
            if (result.isFlag()){
                try {
                    TXSMSUtils.sendShortMessage(telephone, TXSMSUtils.ORDER_NOTICE, code);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        }else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    @PostMapping("/findById")
    public Result findById(Integer id){
        try {
            Map<String, Object> map = service.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
